import {defineStore} from 'pinia'
import { loginApi, getInfoApi, loginOutApi } from '@/api/user'

export const useUserStore=defineStore('user',{
    state:()=>{
        return {
            token: '', // 登录token
            info: {},  // 用户信息
        }
    },
    getters:{
        // token(state) {
        //     return state.token
        // }
    },
    actions:{
        tokenChange(token) {
            this.token=token
        },
        infoChange(info) {
            this.info = info
        },
        // login by login.vue
        login(params) {
            return new Promise((resolve, reject) => {
            loginApi(params)
            .then(res => {
                this.tokenChange(res.data.token)
                this.getInfo(res.data.token)
                .then(infoRes => {
                    resolve(res.data.token)
                })
            })
            })
        },
        // get user info after user logined
        getInfo(params) {
            return new Promise((resolve, reject) => {
            getInfoApi({token:params})
            .then(res => {
                this.infoChange(res.data.info)
                resolve(res.data.info)
            })
            })
        },

        // login out the system after user click the loginOut button
        loginOut({ commit }) {
            loginOutApi()
            .then(res => {

            })
            .catch(error => {

            })
            .finally(() => {
            localStorage.removeItem('tabs')
            localStorage.removeItem('vuex')
            location.reload()
            })
        }
    }
})